package com.wavehi.mapper.impl;

import com.wavehi.mapper.UserMapper;
import com.wavehi.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * @Author WaveHi
 * @Date 18/10/2021 下午 3:46
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description
 */
@Repository
public class UserMapperImpl implements UserMapper {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Boolean insert(User user) {
        //Prepare sql statement
        String sql = "insert into t_user(u_username, u_password) " +
                "values(?, ?)";
        //Insert
        int update = jdbcTemplate.update(sql, user.getUsername(), user.getPassword());
        boolean isCompleted = false;
        if(update > 0) {
            isCompleted = true;
        }
        return true;
    }

    @Override
    public Boolean batchInsert(List<Object[]> users) {
        //Prepare sql statement
        String sql = "insert into t_user(u_username, u_password) " +
                "values(?, ?)";
        //Insert
        int[] ints = jdbcTemplate.batchUpdate(sql, users);
        boolean isCompleted = true;
        for(int num : ints) {
            if(num <= 0) {
                isCompleted = false;
            }
        }
        return isCompleted;
    }

    @Override
    public User selectById(Long id) {
        //Prepare sql statement
        String sql = "select u_id id, u_username username, u_password password " +
                "from t_user " +
                "where u_id=?";
        //Query
        User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
        return user;
    }

    @Override
    public String selectByIdForUsername(Long id) {
        //Prepare sql statement
        String sql = "select u_username username " +
                "from t_user " +
                "where u_id=?";
        //Query
        String username = jdbcTemplate.queryForObject(sql, String.class, id);
        return username;
    }

    @Override
    public List<User> selectAll() {
        //Prepare sql statement
        String sql = "select u_id id, u_username username, u_password password " +
                "from t_user";
        //Query
        List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
        return users;
    }
}
